package com.randy.fundation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;

public class FileUtils {
    public static String readFile(String file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            StringBuilder stringBuilder = new StringBuilder();
            String        ls            = System.getProperty("line.separator");
            String        line          = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(ls);
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public interface Action {
        void yield(File file);
    }

    public static final int UNLIMITED_DEPTH = -1;

    public static void walk(String root, FilenameFilter filter, Action action) {
        walk(new File(root), 0, 1, filter, action);
    }

    public static void walk(File root, FilenameFilter filter, Action action) {
        walk(root, 0, 1, filter, action);
    }

    /**
     * 遍历目录下面的所有文件,并对文件执行相关操作
     *
     * @param root     文件开始目录
     * @param maxDepth 最大深度, -1表示深度不限
     * @param filter   过滤器
     * @param action   操作回调函数
     */

    public static void walk(String root, int maxDepth, FilenameFilter filter, Action action) {
        walk(new File(root), 0, maxDepth, filter, action);
    }

    public static void walk(File root, int maxDepth, FilenameFilter filter, Action action) {
        if (action == null) {
            return;
        }
        walk(root, 0, maxDepth, filter, action);
    }

    private static void walk(File root, int level, int maxDepth, FilenameFilter filter, Action action) {
        if (level >= maxDepth && maxDepth != UNLIMITED_DEPTH) {
            return;
        }
        File[] list = root.listFiles(filter);
        if (list == null) {
            Logger.w("%s not exist", root.getPath());
            return;
        }
        for (File f : list) {
            if (f.isDirectory()) {
                walk(f, level + 1, maxDepth, filter, action);
            } else {
                action.yield(f);
            }
        }
    }
}
